package fire.and.near.challenger;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Response;

import fire.and.near.challenger.camera.CameraHelper;
import fire.and.near.challenger.database.ChallengeModel;
import fire.and.near.challenger.database.ChallengeModel.ChallengeType;
import fire.and.near.challenger.database.ChallengeStatus;
import fire.and.near.challenger.database.DatabaseActivity;
import fire.and.near.challenger.database.DatabaseAsyncTask;
import fire.and.near.challenger.database.DatabaseAsyncTask.DatabaseQueryOptions;
import fire.and.near.challenger.database.DatabaseResponse;
import fire.and.near.challenger.database.TableConstants.ChallengesTable;
import fire.and.near.challenger.database.TableConstants.FriendsTable;
import fire.and.near.challenger.facebook.FacebookActionAdapter;
import fire.and.near.challenger.facebook.FacebookHelper;
import fire.and.near.challenger.facebook.MessageBuilder;
import fire.and.near.challenger.facebook.MessageType;
import fire.and.near.challenger.util.Consts;
import fire.and.near.challenger.web.HttpRequestSender;

public class CompleteChallengeActivity extends Activity implements
		DatabaseActivity {

	private String mCurrentPhotoPath = null;
	private FacebookHelper mFbHelper = LoginActivity.mFbHelper;
	private ChallengeModel mChallenge = null;
	private boolean isWorking = false;
	private boolean fbCompleted = false;
	private boolean dbCompleted = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_complete_challenge);

		if (savedInstanceState == null) {
			initChallenge(getIntent().getExtras());
		}

		final Activity context = this;

		ImageView ivPreview = (ImageView) findViewById(R.id.imageView_photo);
		ivPreview.setImageDrawable(getResources().getDrawable(
				R.drawable.camera_placeholder));
		ivPreview.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mCurrentPhotoPath = CameraHelper
						.dispatchTakePictureIntent(context);
			}
		});

		((EditText) findViewById(R.id.editText_challenge_text))
				.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence s, int start,
							int before, int count) {
						if (s.length() >= Consts.MESSAGE_MAX_LENGTH) {
							Toast.makeText(
									context,
									"Your answer can't be longer than " + Consts.MESSAGE_MAX_LENGTH + " letters",
									Toast.LENGTH_LONG).show();
						}
					}

					@Override
					public void beforeTextChanged(CharSequence s, int start,
							int count, int after) {
					}

					@Override
					public void afterTextChanged(Editable s) {
					}
				});

		String descr = mChallenge.getDescription() == null ? mChallenge
				.getAnswer() : mChallenge.getDescription();

		((TextView) findViewById(R.id.textView_descr)).setText(descr);

		Button btnCompleteChallenge = (Button) findViewById(R.id.button_complete_challenge);

		btnCompleteChallenge.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mChallenge != null) {

					String answer = ((EditText) findViewById(R.id.editText_challenge_text))
							.getText().toString().trim();

					if (answer.length() == 0) {
						Toast.makeText(context, "Write your answer first",
								Toast.LENGTH_SHORT).show();
						return;
					}

					if (mChallenge.getChallengeType() == ChallengeType.PHOTO
							&& mCurrentPhotoPath == null) {
						Toast.makeText(context, "No photo", Toast.LENGTH_LONG)
								.show();
						return;
					}

					mChallenge.setAnswer(answer);

					if (isWorking) {
						return;
					}
					isWorking = true;
					
					findViewById(R.id.progressBar).setVisibility(View.VISIBLE);

					mChallenge.setStatus(ChallengeStatus.PENDING_FOR_FACEBOOK);
					new DatabaseAsyncTask(context,
							DatabaseQueryOptions.CHANGE_STATUS).execute(
							mChallenge.getID(),
							ChallengeStatus.PENDING_FOR_FACEBOOK);
				}
			}
		});
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (mChallenge != null) {
			outState.putInt(ChallengesTable.ID, this.mChallenge.getID());
			outState.putString(ChallengesTable.DESCRIPTION,
					this.mChallenge.getDescription());
			outState.putString(ChallengesTable.ANSWER,
					this.mChallenge.getAnswer());
			outState.putString(ChallengesTable.HASHTAG,
					this.mChallenge.getHashtag());
			outState.putInt(ChallengesTable.CHALLENGE_TYPE,
					this.mChallenge.getChallengeTypeForDatabase());
			outState.putLong(ChallengesTable.CHALLENGER_ID, this.mChallenge
					.getChallenger().getFbID());
			outState.putString(FriendsTable.NAME, this.mChallenge
					.getChallenger().getName());
		}

		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		initChallenge(savedInstanceState);
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (HttpRequestSender.isNetworkAvailable(this)) {
			mFbHelper.onActivityResult(this, requestCode, resultCode, data);
		}

		if (requestCode == CameraHelper.REQUEST_TAKE_PHOTO) {
			ImageView ivPreview = (ImageView) findViewById(R.id.imageView_photo);

			if (resultCode == RESULT_OK) {

				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = true;
				
				BitmapFactory.decodeFile(mCurrentPhotoPath,
						options);

				int width = ivPreview.getWidth();
				int height = ivPreview.getHeight();

				Log.i("CompleteChallengeAct", "" + width + "x" + height);

				options = CameraHelper
						.makeSampleOptions(this, options, width, height);
				
				options.inJustDecodeBounds = false;

				final Bitmap bitmap = BitmapFactory.decodeFile(
						mCurrentPhotoPath, options);

				ivPreview.setImageBitmap(bitmap);
			} else {
				mCurrentPhotoPath = null;

				ivPreview.setImageDrawable(getResources().getDrawable(
						R.drawable.camera_placeholder));
			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_logout) {
			if (HttpRequestSender.isNetworkAvailable(this)) {
				LoginActivity.mFbHelper.logout();
			}

			finish();
			return true;
		}

		if (id == R.id.action_details) {
			Intent i = new Intent(this, UserDetailsActivity.class);
			startActivity(i);

			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void initChallenge(Bundle extras) {
		if (extras != null) {

			this.mChallenge = new ChallengeModel();
			this.mChallenge.setID(extras.getInt(ChallengesTable.ID));
			this.mChallenge.setDescription(extras
					.getString(ChallengesTable.DESCRIPTION));
			this.mChallenge.setAnswer(extras.getString(ChallengesTable.ANSWER));
			this.mChallenge.setHashtag(extras
					.getString(ChallengesTable.HASHTAG));
			this.mChallenge.setChallengeType(extras
					.getInt(ChallengesTable.CHALLENGE_TYPE));
			this.mChallenge.getChallenger().setFbID(
					extras.getLong(ChallengesTable.CHALLENGER_ID));
			this.mChallenge.setAccepted(extras
					.getBoolean(ChallengesTable.ACCEPTED));
		}
	}

	@Override
	public void processDatabaseResponse(DatabaseResponse result) {
		final Activity context = this;

		if (result.isSuccessful()) {
			if (result.getOption() == DatabaseQueryOptions.CHANGE_STATUS) {

				if (mChallenge.getStatus() == ChallengeStatus.PENDING_FOR_FACEBOOK) {

					Bitmap bitmap = null;

					if (mCurrentPhotoPath != null) {
						bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
					}

					Log.i("ZMIQTA WE ACT", "" + mChallenge.getID() + " : "
							+ mChallenge.getAnswer());

					new DatabaseAsyncTask(this,
							DatabaseQueryOptions.SAVE_ANSWER).execute(
							mChallenge.getID(), mChallenge.getAnswer());

					if (!HttpRequestSender.isNetworkAvailable(this)) {
						Toast.makeText(this,
								"No Internet access. Marked as 'pending'.",
								Toast.LENGTH_LONG).show();

						fbCompleted = true;

						new DatabaseAsyncTask(this,
								DatabaseQueryOptions.SET_PHOTO)
								.execute(this.mChallenge.getID(),
										this.mCurrentPhotoPath);
						return;
					} else {
						new DatabaseAsyncTask(this,
								DatabaseQueryOptions.COMPLETE)
								.execute(this.mChallenge.getID());
					}

					MessageBuilder msgBuilder = null;

					msgBuilder = new MessageBuilder(
							mChallenge.getDescription(),
							mChallenge.getAnswer(), mChallenge.getHashtag(),
							MessageType.CompleteChallenge);

					mFbHelper.postStatusUpdate(context, msgBuilder.build(), ""
							+ mChallenge.getChallenger().getFbID(), bitmap,
							new FacebookActionAdapter() {
								@Override
								public void onActionCompleted(Response response) {

									if (response.getError() == null) {
										Log.i("UploadStatusWithPic", "Success");
										Toast.makeText(context,
												"Posted on facebook",
												Toast.LENGTH_LONG).show();
									} else {
										Log.i("UploadStatusWithPic",
												response.toString());
									}

									fbCompleted = true;
									if (dbCompleted) {
										finish();
									}
								}
							});
				}
			}
			if (result.getOption() == DatabaseQueryOptions.COMPLETE) {
				Toast.makeText(this, "Challenge added to history",
						Toast.LENGTH_LONG).show();

				// TODO:

				new DatabaseAsyncTask(this, DatabaseQueryOptions.SET_PHOTO)
						.execute(this.mChallenge.getID(),
								this.mCurrentPhotoPath);
			}
			if (result.getOption() == DatabaseQueryOptions.SET_PHOTO) {
				dbCompleted = true;
				if (fbCompleted) {
					finish();
				}
			}
		}
	}

	@Override
	public void setDatabaseWorking(boolean working) {
		// What about facebook posting....
//		if (working) {
//			findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
//		} else {
//			findViewById(R.id.progressBar).setVisibility(View.GONE);
//		}
	}

}
